<?php

namespace app\service\payment\gateway;

use app\libs\AirwallexSDK\Action\PaymentIntent;
use app\libs\AirwallexSDK\Build\PaymentIntentBuilder;
use app\model\Notify;
use app\model\Orders;
use app\model\ShopsPayment;
use think\helper\Arr;
use think\Request;

class AirwallexService extends PaymentBase implements PaymentInterface
{

    const CHECKOUT_URL_LIVE = 'https://checkout.airwallex.com';
    const CHECK_URL_SANDBOX = 'https://checkout-demo.airwallex.com';

    /**
     * @param Orders $order
     * @param Request $request
     * @return array
     * @throws \Exception
     * @desc 创建订单
     */
    public function placeOrder(Orders $order, Request $request):array
    {
        $log = null;
        try {
            $client = new PaymentIntent($order->payment);
            $builder = new PaymentIntentBuilder($order);
            $result = $client->create_payment_intent($builder);
            $log = Notify::saveParams($order->id, ['params' => $builder->toArray(), 'result' => $result],Notify::TYPE_PLACE_ORDER,$order->pay_method);
            if (empty($result)) throw new \Exception('create airwallex order error');
            $transaction_id = Arr::get($result,'id','');
            $client_secret = Arr::get($result,'client_secret','');
            $pay_result = $result;
            $order->trade_no = $transaction_id;
            $order->save();
            $approval_url = $this->get_payment_url($pay_result,$order);
            return compact('client_secret', 'transaction_id', 'pay_result','approval_url');
        }catch (\Exception $e){
            if($log){
                $logParams = $log->params;
                $logParams['error'] = $e->getMessage();
                $log->save();
            }
            throw $e;
        }
    }


    //获取支付链接
    public function get_payment_url(array $result,Orders $order)
    {
        $path = '/#/standalone/checkout';
        $theme = [
            'fonts'=>[
                [
                    'src'=>'https://checkout.airwallex.com/fonts/CircularXXWeb/CircularXXWeb-Regular.woff2',
                    'family'=>'AxLLCircular',
                    'weight'=>400
                ],
            ],
        ];

        //withBilling:true,requiredBillingContactFields: ['name''email ,'address']
        $query = [
            'client_secret'=>$result['client_secret'],
            'intent_id'=>$result['id'],
            'currency'=>$order->present_currency,
            'mode'=>'payment',
            'theme'=>urlencode(json_encode($theme,JSON_UNESCAPED_UNICODE)),
            'locale'=>'en',
            //'methods'=>urlencode(json_encode(['card'])),
            'sessionId'=>session_id(),
            'withBilling'=>true,
            'requiredBillingContactFields'=> json_encode(['name','email','address'],JSON_UNESCAPED_UNICODE),
        ];
        $queryStr = http_build_query($query);
        $baseUrl = $order->payment->mode == ShopsPayment::MODE_LIVE ? self::CHECKOUT_URL_LIVE : self::CHECK_URL_SANDBOX;
        return sprintf('%s%s?%s',$baseUrl,$path,$queryStr);

    }
    

    //确认支付
    public function confirmPayment()
    {
        //todo
        return false;
    }

    protected function getPaymentMethod(array $account,Orders $order)
    {
        return [
            'request_id'=>uniqid(),
            'payment_method'=>[
                'card'=>[
                    'billing'=>[
                        'address'=>[
                            'city'=>$order->billingAddress->city,
                            'country_code'=>$order->billingAddress->country_code,
                            'postcode'=>$order->billingAddress->zip,
                            'state'=>$order->billingAddress->province,
                            'street'=>$order->billingAddress->address1,
                        ],
                        'email'=>$order->email,
                        'first_name'=>$order->billingAddress->first_name,
                        'last_name'=>$order->billingAddress->last_name,
                        'phone_number'=>$order->billingAddress->phone,
                    ],
                    'cvc'=>$account['verificationCode'],
                    'expiry_month'=>$account['expiryMonth'],
                    'expiry_year'=>$account['expiryYear'],
                    'name'=>$account['holderName'],
                    'number'=>$account['number'],
                ],
            ],
            'type'=>'card',
            'payment_method_options'=>[
                'card'=>[
                   'authorization_type'=>'final_auth',
                    'auto_capture'=>true,
                ],
            ],
        ];
    }

    public function repurchase(Orders $order, Request $request){
        //todo
        return false;
    }
}